package org.radar.agent.jmx;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;

/**
 * JMX注册器
 *
 * @author zhangcs
 */
public class JmxRegistry {

    private static final String JmxBeanNamePrefix = "RadarJmxBean:name=";

    public static boolean registry(int port) {
        return registry("127.0.0.1", port);
    }

    public static boolean registry(String host, int port) {
        // 判断当前是否已启用JMX

        try {
            // 注册MBean
            MBeanServer mbs = MBeanServerFactory.createMBeanServer();
            mbs.registerMBean(ManagementFactory.getThreadMXBean(), new ObjectName(JmxBeanNamePrefix + "Thread"));
            mbs.registerMBean(ManagementFactory.getMemoryMXBean(), new ObjectName(JmxBeanNamePrefix + "Memory"));
            mbs.registerMBean(ManagementFactory.getClassLoadingMXBean(), new ObjectName(JmxBeanNamePrefix + "ClassLoading"));
            mbs.registerMBean(ManagementFactory.getRuntimeMXBean(), new ObjectName(JmxBeanNamePrefix + "Runtime"));
            mbs.registerMBean(ManagementFactory.getOperatingSystemMXBean(), new ObjectName(JmxBeanNamePrefix + "OperatingSystem"));

            // 注册端口
            LocateRegistry.createRegistry(port);

            // 构建服务
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
            cs.start();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
